<?php

    class Model_Place extends Joob_Db_Table {
    	
    	protected $key = "id";
	
		protected $db = "places";
       
        public function add(){
            $this->setOption('time',time());
            return $this->insert('group_id,owner_id,name,avatar,address, website,description,lng,lat,since');
        }
       
    	public function deletePhotos(){
            $sql = "DELETE FROM photos WHERE place_id = ".$this->id;
            return SQL::update($sql);
        }
       
        public static function getByUser($user_id,$page,$page_size){
            $place = new Model_Place();
            return $place->search('owner_id='.$user_id,'*', $page*$page_size.','.$page_size);
        }
       
        public function getNearPlaces($group_id,$dist,$page,$page_size){
           
           
            // R = earth’s mean radius
            $R = 6371;
            // first-cut bounding box (in degrees)
            $maxLat = $this->lat + rad2deg($dist/$R);
            $minLat = $this->lat - rad2deg($dist/$R);
            // compensate for degrees longitude getting smaller with increasing latitude
            $maxLng = $this->lng + rad2deg($dist/$R/cos(deg2rad($this->lat)));
            $minLng = $this->lng - rad2deg($dist/$R/cos(deg2rad($this->lat)));
           
            $condition = 'id <> '.$this->id.' and activated=1 and (lat < '.$maxLat.') and (lat > '.$minLat.') and (lng < '.$maxLng.') and (lng > '.$minLng.')';
            if($group_id>0){
                $condition.= ' and group_id='.$group_id;
            }
           
            $nearplaces = $this->search($condition, "id,name,lat,lng,address,rank", $page*$page_size.','.$page_size,' rank DESC');
			
			$result = array();
// 			var_dump($nearplaces);die();*/
			foreach($nearplaces as $nearplace){
	//			var_dump($listNeighbour);die();
				$real_distance = Model_Map::getDistance($this->lat, $this->lng, $nearplace->lat, $nearplace->lng);
				$real_distance = explode('.',$real_distance);
				$distance = $real_distance[0];
				if($real_distance[1]) $distance .= ','.substr($real_distance[1],0,3);
				$nearplace = array('id'=>$nearplace->id, 
						'name'=>$nearplace->name,
						'address'=>$nearplace->address,
						'rank'=>$nearplace->rank, 
						'lat'=>$nearplace->lat,
						'lng'=>$nearplace->lng,
						'distance'=>$distance
				);
				$result[] = $nearplace;
			}
			return $result;
        }
       
        public function countRank(){
            $rate_total=0;
            for($i=1;$i<=5;$i++){
                $rate = new Model_Vote();
                $num_rate = $rate->search(" type='place' and target_id=".$this->id. " and value= ".$i,' count(id) as num_rate','1');
                $rate_total += (int)$num_rate[0]->num_rate * (int)$i;
            }
            $rate_level = ceil($rate_total / (int)$this->total_vote);
            $this->setOption('rank',$rate_level);
            $this->edit('rank');
            return $rate_level;
        }
       
        public function getInfo($viewer_id)	{
        	if($viewer_id==0){
        		$checkVoted = -1;
				$checkCheckedIn = -1;
        	}
			else{
				$checkVoted = (int)Model_Vote::checkVotedStatic($viewer_id,$this->id,'place');
				$checkCheckedIn = (int)Model_Checkin::checkCheckedInStatic($viewer_id,$this->id);
			}
        	$checkinInfo = $this->getCheckinInfo();
        	return array('id'=>$this->id, 'name'=>$this->name, 'avatar'=>$this->avatar,
        		'website'=>$this->website, 'address'=>$this->address, 'description'=>$this->description,
        		'lng'=>$this->lng, 'lat'=>$this->lat, 'rank'=>$this->rank, 'total_vote'=>$this->total_vote,
        		'total_checkin'=>$checkinInfo['totalCheckin'],
        		'check_voted'=>$checkVoted,'check_checkedin'=>$checkCheckedIn,
				'total_being'=>$checkinInfo['totalBeing'], 'total_been'=>$checkinInfo['totalBeen'],
				'user_being'=>$checkinInfo['userBeing'],
				'user_been'=>$checkinInfo['userBeen']);
        }
		
		public function getCheckinInfo(){
			$checkin = new Model_Checkin();
			$checkin = $checkin->search('place_id = '.$this->id,'id,time_out,user_id,user_name');
			$totalCheckin = count($checkin);
			$totalBeing = 0;
			$totalBeen = 0;
			$userBeen = array();
			$userBeenId = array();
			$userBeing = array();
			foreach($checkin as $check){
				if($check->time_out==null){
					$totalBeing++;
					$userBeing[] = array('user_id'=>$check->user_id,'user_name'=>$check->user_name);
				} 
				if(!in_array($check->user_id,$userBeenId)){
					$totalBeen++;
					$userBeenId[] = $check->user_id;
					$userBeen[] = array('user_id'=>$check->user_id,'user_name'=>$check->user_name);
				}
			}
			return array('totalCheckin'=>$totalCheckin,'totalBeing'=>$totalBeing,'totalBeen'=>$totalBeen,
				'userBeing'=>$userBeing,'userBeen'=>$userBeen);
		}
		
		public function getUserBeing(){
			$checkin = new Model_Checkin();
			return $checkin->search('place_id = '.$this->id.' and time_out = null','place_id,user_id,user_name,user_avatar');
		}
		
		public function getUserBeen(){
			$checkin = new Model_Checkin();
			return $checkin->search('place_id = '.$this->id,'place_id,user_id,user_name,user_avatar');
		}
		
		public function addTotalVote(){
			$this->setOption('total_vote',++$this->total_vote);
            $this->edit('total_vote');
		}
		
		public function vote($user_id,$value){
			$vote = new Model_Vote();//$user_id,$target_id,$type,$value
			$vote->newVote($user_id,$this->id,'place',$value);
			if($vote->checkVoted()) return false;
			else{
				$vote->addVote();
				$this->addTotalVote();
				$this->countRank();
			}
		}
       
        public $id, $owner_id, $group_id, $name, $avatar, $website, $address;
        public $description, $total_in, $total_vote, $rank;
        public $lng, $lat;
    }
?>